import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

//bcprov-jdk16-146.jar
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class posMacCalc {
    static{
        Security.addProvider(new BouncyCastleProvider());
    }
    
    public static void main(String[] args) throws Exception {
        //zak(mackey)
        byte[] MACKEY = new byte[]{31, 31, 31, 31, 31, 31, 31, 31};
        //待计算数据
        byte[] data = new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        //进行分组
        int group = (data.length + (8 - 1)) / 8;
        //偏移量
        int offset = 0 ;
        //输入计算数据
        byte[] edata = null;
        for(int i = 0 ; i < group; i++){
            byte[] temp = new byte[8];
            if(i != group - 1){ 
                System.arraycopy(data, offset, temp, 0, 8);
                offset += 8;
            }else{//只有最后一组数据才进行填充0x00
                System.arraycopy(data, offset, temp, 0, data.length - offset);
            }


            if(i != 0){//只有第一次不做异或
                temp = XOR(edata,temp);
            }
            edata = desedeEn(MACKEY,temp);
        }
        System.out.println(java.util.Arrays.toString(byte2Int(edata)));
        System.out.println(Hex.encodeHexString(edata));
    }
    
    public static byte[] XOR(byte[] edata, byte[] temp) {
        byte [] result = new byte[8];
        for (int i = 0 , j = result.length ; i < j; i++) {
            result [i] = (byte) (edata[i] ^ temp[i]);
        }
        return result;
    }
    
    public static int[] byte2Int(byte[] data) {
    int[] result = new int[data.length];
    
    for(int i = 0; i < data.length; i++) {
    if (data[i] < 0) {
    result[i] = data[i] + 256;
    } else {
    result[i] = data[i];
    }
    }
    
    return result;
    }
    
    public static byte[] desedeEn(byte[] key,byte[] data){
        byte[] result = null;
        try {
            SecretKey secretKey = getSecretKeySpec(key);
            Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding","BC");

            cipher.init(Cipher.ENCRYPT_MODE, secretKey,new IvParameterSpec(new byte[8]));
            //初始化向量为0,即异或不改变原始数据

            result = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    private static SecretKey getSecretKeySpec(byte[] keyB) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("Des");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyB,"Des");
        return secretKeyFactory.generateSecret(secretKeySpec);
    }
}